package com.stooscloud.provider.impl.factory;

import com.stooscloud.DESUtil;
import com.stooscloud.JacksonUtil;
import com.stooscloud.base.exception.BusinessException;
import com.stooscloud.provider.impl.doman.GeoC8;
import com.stooscloud.provider.impl.doman.Idcheck;
import com.stooscloud.provider.inter.factory.BuilderObjFactory;
import com.stooscloud.provider.util.DTOBuilder;
import config.properties.WsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class GeoC8BuilderFactory implements BuilderObjFactory<GeoC8> {
    @Resource
    WsProperties wsProperties;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.password}")
    private String password;

    @Override
    public GeoC8 builderObj(Object obj) {
        GeoC8 geoC8 = null;
        try {
            if (obj instanceof HttpServletRequest){
                HttpServletRequest request = (HttpServletRequest)obj;
                geoC8 = (GeoC8) DTOBuilder.getDTO(request,Idcheck.class);
            }else if(obj instanceof String){
                String json = (String)obj;
                geoC8 = JacksonUtil.parseJson(json,GeoC8.class);
            }else{
                log.error("没有该类型的报文,不能解析报文");
                throw new BusinessException(1007,"没有该类型的报文");
            }
        }catch (Exception e){
            log.error("映射obj到实体类失败,请检查报文");
            throw new BusinessException(1008,"报文转换失败");
        }

        log.info("解析报文成功");
        decrypt(geoC8);
        log.info("解密报文信息成功");
        geoC8.setAuthCode(getId(geoC8));
        geoC8.setInnerIfType("C8");
        return geoC8;
    }

    /**
     * 解密字段信息
     * @param geoC8
     */
    private void decrypt(GeoC8 geoC8){
        try {
            if (StringUtils.isBlank(geoC8.getRealName()))
                geoC8.setRealName("查询");
        } catch (Exception e) {
            log.error("解密信息失败!",e);
            throw new BusinessException(1006,"解密信息失败!",e);
        }
    }

    /**
     * 获取唯一ID
     * @return
     */
    private String getId(GeoC8 geoC8){
        log.info("开始生成系统唯一编号");
        long timeMillis = System.currentTimeMillis()/1000;
        String userno = "00" + wsProperties.getGeo().getUno();
        return String.valueOf(timeMillis)+userno+geoC8.getAuthCode();
    }
}
